package com.eca.emas.daemon;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.eca.emas.daemon.shared.EMASMailManager;
import com.eca.emas.daemon.shared.MySQLConnectionManager;
import com.eca.emas.daemon.shared.SQLConstants;
import com.eca.emas.daemon.shared.Sensor;
import com.eca.emas.daemon.shared.SensorData;

public class WiregateManager {

	private static WiregateManager instance = new WiregateManager();

	private static ArrayList<WiregateServer> servers;

	private WiregateManager() {
	}

	public void updateServerList() {
		servers = new ArrayList<WiregateServer>();
		try {
			MySQLConnectionManager manager = MySQLConnectionManager
					.getInstance();
			ResultSet set = manager.selectQuery("SELECT * FROM "
					+ SQLConstants.location_table);
			while (set.next()) {
				String ip = set.getString(SQLConstants.location_ip);
				int location_id = set.getInt(SQLConstants.location_id);
				String password = set.getString(SQLConstants.location_password);
				WiregateServer server = new WiregateServer(ip, password,
						location_id);
				boolean succsess = server.updateSensorsViaSSH();
				if (succsess) {
					servers.add(server);
				}
			}

			System.out.println("Server and Sensor List Updated...");
		} catch (SQLException e) {
			EMASMailManager.getInstance().sendErrorMessageToAllRecipients(
					EMASMailManager.ERROR_SQL, e);
			e.printStackTrace();
		}
	}

	public void updateAllServerData() {
		if (servers != null) {
			WiregateDataHandler handler = new WiregateDataHandler();
			for (WiregateServer server : servers) {
				ArrayList<Sensor> sensors = server.getSensors();
				ArrayList<SensorData> sensorDatas = new ArrayList<SensorData>();
				for (Sensor sensor : sensors) {
					SensorData data = handler.getTemperaturDataForSensor(
							sensor, server);
					if (data.isValidData()) {
						sensorDatas.add(data);
					}
				}
				if (sensorDatas != null && !sensorDatas.isEmpty()) {
					MySQLConnectionManager manager = MySQLConnectionManager
							.getInstance();
					manager.inserMultipleSensorData(sensorDatas);
				}
			}
		}
	}

	public void removeServer(WiregateServer server) {
		servers.remove(server);
	}

	public static WiregateManager getInstance() {
		if (instance == null) {
			instance = new WiregateManager();
		}
		return instance;
	}
}
